package com.spring.security.validate.code.impl;

import com.spring.security.validate.code.ValidateCode;
import com.spring.security.validate.code.ValidateCodeException;
import com.spring.security.validate.code.ValidateCodeRepository;
import com.spring.security.validate.code.ValidateCodeType;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

@Component
public class RedisValidateCodeRepository implements ValidateCodeRepository {
    /**
     * redis操作
     */
    @Autowired
    private RedisTemplate redisTemplate;
    //验证码自动清理时间  分钟
    private final static Integer TIME_OUT = 30;

    /**
     * 添加验证码
     *
     * @param request
     * @param code
     * @param validateCodeType
     */
    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType validateCodeType) {
        redisTemplate.opsForValue().set(buildKey(request, validateCodeType), code, TIME_OUT, TimeUnit.MINUTES);
    }

    /**
     * 查询验证码
     *
     * @param request
     * @param validateCodeType
     * @return
     */
    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {
        Object value = redisTemplate.opsForValue().get(buildKey(request, validateCodeType));
        if (value == null) {
            return null;
        } else {
            return (ValidateCode) value;
        }

    }

    /**
     * 删除验证码
     *
     * @param request
     * @param validateCodeType
     */
    @Override
    public void remove(ServletWebRequest request, ValidateCodeType validateCodeType) {
        redisTemplate.delete(buildKey(request, validateCodeType));
    }

    /**
     * 解析请求头
     *
     * @param request
     * @param validateCodeType
     * @return
     */
    private String buildKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
        String deviceId = request.getHeader("deviceId");
        if (StringUtils.isBlank(deviceId)) {
            throw new ValidateCodeException("请在请求头中设置deviceId");
        }
        return "code:" + validateCodeType.toString().toLowerCase() + ":" + deviceId;
    }
}
